//
//  MSDayStatisticsController.m
//  觅尚
//
//  Created by No.8 on 2019/3/26.
//  Copyright © 2019 No.8. All rights reserved.
//

#import "MSDayStatisticsController.h"
#import "MSDayCell.h"
#import "MSDayProgressView.h"
#import "CircleProgressView.h"
#import "MSKaoqinDayController.h"
#import "MSDayStatisticsModel.h"
#import "MSDayTimeView.h"

@interface MSDayStatisticsController ()<UITableViewDataSource,UITableViewDelegate,MSDayCellDelegate,MSDayTimeViewDelegate>

/** tableView*/
@property(nonatomic,strong)UITableView *tableView;

@property (nonatomic, strong) CircleProgressView *circleProgress;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) MSDayTimeView *datePickerView;

@property (nonatomic, strong) UIView *lightGrayView;
/** staffCount*/
@property(nonatomic,strong)NSString *staffCount;

/** staffCount*/
@property(nonatomic,strong)NSMutableArray *departmentlistArray;

/** <#name#>*/
@property(nonatomic,strong)NSString *Depid;


/** <#name#>*/
@property(nonatomic,strong)NSString  *TimeStr;

/** <#name#>*/
@property(nonatomic,strong)UILabel *timeLabel;

/** <#name#>*/
@property(nonatomic,strong)UIView *backView;





@end

@implementation MSDayStatisticsController
- (int)navBarBottom {
    if ([WRNavigationBar isIphoneX]) {
        return 88;
    } else {
        return 64;
    }
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];
    self.navigationController.navigationBar.hidden = YES;
    self.departmentlistArray = [NSMutableArray new];
    Prepare *header = [Prepare headerWithRefreshingTarget:self refreshingAction:@selector(MJChiBaoZiHeaderRefresh)];
    // 隐藏时间
    header.lastUpdatedTimeLabel.hidden = YES;
    header.stateLabel.hidden = YES;
    // 马上进入刷新状态
    self.tableView.mj_header = header;
    [self.tableView.mj_header beginRefreshing];
    
    
}
- (void)MJChiBaoZiHeaderRefresh{
    
    [self ReloadData];
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:YES];
    self.navigationController.navigationBar.hidden = YES;
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = backgroundcolor;
    
    [self CreatView];
    
    [self tableView];
    
    
    
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(progressTimer:) userInfo:nil repeats:YES];
}

- (void)ReloadData{
    [MBManager showLoading];
    [self.departmentlistArray removeAllObjects];
    NSDictionary * params = @{@"busid":[WYCAccountTool unarchivebelongBusid],@"queryTime":@"day",@"depid":[WYCAccountTool unarchivebelongDepid],@"roleId":[WYCAccountTool unarchivebelongRolid],@"dateTime":self.timeLabel.text};
    WYCLog(@"------%@",params);
    [HTTPRequest POST:MSgetDepartmentAttendance params:params succeed:^(id responseObject) {
        WYCLog(@"------%@",responseObject);
        if (CodeStr) {
            [self.tableView.mj_header endRefreshing];
            [MBManager hideAlert];
            self.staffCount = [NSString stringWithFormat:@"%@/%@",responseObject[@"data"][@"punchCount"],responseObject[@"data"][@"staffCount"]];
            self.departmentlistArray = [MSDayStatisticsModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"][@"departmentlist"]];
        }else{
            [self.tableView.mj_header endRefreshing];
             [MBManager hideAlert];
            [MBManager showBriefAlert:responseObject[@"msg"]];
        }
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        [self.tableView.mj_header endRefreshing];
         [MBManager hideAlert];
        [MBManager showBriefAlert:Failed];
    }];
}




- (void)progressTimer:(NSTimer *)timer
{
    NSArray *array = [self.staffCount componentsSeparatedByString:@"/"]; //从字符A中分隔成2个元素的数组
    self.circleProgress.percent = [array[0] intValue] / [array[1] intValue];
    self.circleProgress.centerLabel.text = [NSString stringWithFormat:@"%@",self.staffCount];
    
    self.circleProgress.titleLabel.text = @"考勤人数/应到人数";
    self.circleProgress.titleLabel.font = [UIFont systemFontOfSize:SYRealValue(28 / 2)];
    if(self.circleProgress.percent > 1)
    {
        [self.timer invalidate];
    }
}

- (void)CreatView{
    
    UIView * HeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 1200 * px)];
    HeaderView.backgroundColor = backgroundcolor;
    [self.view addSubview:HeaderView];
    
    UIView * timeView = [[UIView alloc] initWithFrame:CGRectMake(50 * px, 50 * px, ScreenWidth * 0.6, 120 * px)];
    timeView.layer.cornerRadius = 10 * px;
    timeView.layer.borderWidth = 1;
    timeView.layer.borderColor = WYCRGBColor(33, 46, 45).CGColor;
    [HeaderView addSubview:timeView];
    
    
    /** 日历图标*/
    UIButton * TimeButton = [[UIButton alloc] initWithFrame:CGRectMake(30 * px, 30 * px, 60 * px, 60 * px)];
//    [TimeButton setImage:[UIImage imageNamed:@"calendar icon"] forState:UIControlStateNormal];
    [TimeButton setBackgroundImage:[UIImage imageNamed:@"calendar icon"] forState:UIControlStateNormal];
    TimeButton.imageView.contentMode = UIViewContentModeScaleAspectFit;
    [TimeButton addTarget:self action:@selector(TimeButtonClick) forControlEvents:UIControlEventTouchUpInside];
//    TimeButton.backgroundColor = [UIColor redColor];
    [timeView addSubview:TimeButton];
    
    /** 左按钮*/
    UIButton *  leftButton= [[UIButton alloc] initWithFrame:CGRectMake(CGRectGetMaxX(TimeButton.frame) + 40 * px, TimeButton.y, 40 * px, TimeButton.height)];
    [leftButton setBackgroundImage:[UIImage imageNamed:@"日期选择-左箭头"] forState:UIControlStateNormal];
//    [leftButton addTarget:self action:@selector(leftButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [timeView addSubview:leftButton];
    
    
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY-MM-dd"];
    NSDate *datenow = [NSDate date];
    NSString *currentTimeString = [formatter stringFromDate:datenow];
    self.TimeStr = currentTimeString;
    /** 时间*/
    UILabel * timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(leftButton.frame) + 40 * px, TimeButton.y, timeView.width / 2, TimeButton.height)];
    timeLabel.textColor = [UIColor grayColor];
    timeLabel.text = [NSString stringWithFormat:@"%@",self.TimeStr];
    timeLabel.textAlignment = NSTextAlignmentCenter;
    timeLabel.font = [UIFont systemFontOfSize:SYRealValue(30 / 2)];
    [timeView addSubview:timeLabel];
    self.timeLabel = timeLabel;
    
    /** 右按钮*/
    UIButton *  rightButton= [[UIButton alloc] initWithFrame:CGRectMake(CGRectGetMaxX(timeLabel.frame) + 40 * px, TimeButton.y, 40 * px, TimeButton.height)];
    [rightButton setBackgroundImage:[UIImage imageNamed:@"日期选择-右箭头"] forState:UIControlStateNormal];
//    [rightButton addTarget:self action:@selector(leftButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [timeView addSubview:rightButton];
    
    
    /** 日历按钮*/
    UIImageView * AttendanceIMG = [[UIImageView alloc] initWithFrame:CGRectMake(timeView.x, 950 * px, TimeButton.width, TimeButton.height)];
    AttendanceIMG.image = [UIImage imageNamed:@"消费"];
    [HeaderView addSubview:AttendanceIMG];
    
    
    self.circleProgress = [[CircleProgressView alloc] initWithFrame:CGRectMake(ScreenWidth / 4, CGRectGetMaxY(timeView.frame) + 50 * px, ScreenWidth / 2, ScreenWidth / 2)];
    self.circleProgress.backgroundColor = [UIColor clearColor];
    [HeaderView addSubview:self.circleProgress];
    
    
    /** 部门出勤*/
    UILabel * AttendanceLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(AttendanceIMG.frame) + 30 * px, AttendanceIMG.y, 260 * px, AttendanceIMG.height)];
    AttendanceLabel.textColor = [UIColor whiteColor];
    AttendanceLabel.text = @"部门出勤";
    AttendanceLabel.font = [UIFont boldSystemFontOfSize:SYRealValue(36 / 2)];
    [HeaderView addSubview:AttendanceLabel];
    
    
    UIView * linView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(AttendanceLabel.frame) + 30 * px, HeaderView.width, 1)];
    linView.backgroundColor = WYCRGBColor(31, 44, 62);
    [HeaderView addSubview:linView];
    
    
    CGFloat titlelabelY = CGRectGetMaxY(linView.frame) + 30 * px;
    CGFloat titlelabelH = 80 * px;
    CGFloat titlelabelW = ScreenWidth / 3;
    NSArray * titleArray = @[@"部门",@"考勤人数/应到人数",@"详情"];
    for (NSInteger i = 0; i < titleArray.count; i ++) {
        /** <#name#>*/
        UILabel * titlelabel = [[UILabel alloc] init];
        titlelabel.x = titlelabelW * i;
        titlelabel.y = titlelabelY;
        titlelabel.width = titlelabelW;
        titlelabel.height = titlelabelH;
        titlelabel.textColor = [UIColor whiteColor];
        titlelabel.text = titleArray[i];
        titlelabel.textAlignment = NSTextAlignmentCenter;
        titlelabel.font = [UIFont systemFontOfSize:SYRealValue(28 / 2)];
        [HeaderView addSubview:titlelabel];
    }
    
    
    UIView * titleView = [[UIView alloc] initWithFrame:CGRectMake(60 * px, CGRectGetMaxY(linView.frame) + 140 * px, linView.width - 120 * px, 1)];
    titleView.backgroundColor = linView.backgroundColor;
    [HeaderView addSubview:titleView];
    self.tableView.tableHeaderView = HeaderView;
    
    
}
- (void)TimeButtonClick{
    
    WYCLogFunc;
    
    UIView * view = [[UIView alloc] init];
    view.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight);
    view.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
    [[UIApplication sharedApplication].keyWindow  addSubview:view];
    self.backView = view;
    
    
    
    
    
    
    self.datePickerView = [[MSDayTimeView alloc] initWithFrame:CGRectMake(0, view.height - 225, view.width, 225) withTimeShowMode:ShowAllTime withIsShowTodayDate:YES];
    self.datePickerView.backgroundColor = [UIColor whiteColor];
    self.datePickerView.delegate = self;
    [view addSubview:self.datePickerView];
    //    self.datePickerView.hidden = YES;
    
    self.lightGrayView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, view.width, view.height - 225)];
    [view addSubview:self.lightGrayView];
    self.lightGrayView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
    self.lightGrayView.hidden = YES;
    // 单击的 Recognizer(_typeBottomView添加手势)
    UITapGestureRecognizer* singleRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(lightGrayViewSingleTapFromAction)];
    singleRecognizer.numberOfTapsRequired = 1; // 单击
    [self.lightGrayView addGestureRecognizer:singleRecognizer];
}

- (void)BtnAction {
    self.datePickerView.hidden = NO;
    __weak typeof (self) weakSelf = self;
    [UIView animateWithDuration:0.3 // 动画时长
                          delay:0.0 // 动画延迟
                        options:UIViewAnimationOptionCurveEaseIn // 动画过渡效果
                     animations:^{
                         __strong typeof (weakSelf) strongSelf = weakSelf;
                         strongSelf.datePickerView.frame = CGRectMake(0, ScreenHeight - 225, ScreenWidth, 225);
                     }
                     completion:^(BOOL finished) {
                         // 动画完成后执行
                         __strong typeof (weakSelf) strongSelf = weakSelf;
                         strongSelf.lightGrayView.hidden = NO;
                     }];
    
}

- (void)lightGrayViewSingleTapFromAction {
    __weak typeof (self) weakSelf = self;
    [UIView animateWithDuration:0.3 // 动画时长
                          delay:0.0 // 动画延迟
                        options:UIViewAnimationOptionCurveEaseIn // 动画过渡效果
                     animations:^{
                         __strong typeof (weakSelf) strongSelf = weakSelf;
                         strongSelf.lightGrayView.hidden = YES;
                         strongSelf.datePickerView.frame = CGRectMake(0, ScreenHeight + 225, ScreenWidth, 225);
                     }
                     completion:^(BOOL finished) {
                         // 动画完成后执行
                         __strong typeof (weakSelf) strongSelf = weakSelf;
                         //                         strongSelf.datePickerView.hidden = YES;
                         strongSelf.backView.hidden = YES;
                     }];
    
}

#pragma mark - DatePickerViewDelegate
- (void)DatePickerView:(NSString *)year withMonth:(NSString *)month withDay:(NSString *)day withDate:(NSString *)date withTag:(NSInteger)tag{
    //确定
    if (tag == 1001) {
        self.timeLabel.text = [NSString stringWithFormat:@"%@",date];
        [self lightGrayViewSingleTapFromAction];
        [self ReloadData];
    }else{//1002：取消
        self.timeLabel.text = [NSString stringWithFormat:@"%@",self.TimeStr];
        [self lightGrayViewSingleTapFromAction];
    }
}
/** 表视图*/
- (UITableView *)tableView{
    self.extendedLayoutIncludesOpaqueBars = YES;
    if (!_tableView) {
        
        if (@available(iOS 11.0, *)) {
            
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            
        } else {
            
            self.automaticallyAdjustsScrollViewInsets = NO;
            
        }
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight - [self navBarBottom] - 150 * px) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
        _tableView.separatorColor = BackViewColor;
        [self.view addSubview:self.tableView];
    }
    return _tableView;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.departmentlistArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 200 * px;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    MSDayCell * cell = [MSDayCell cellWithTableView:tableView];
    tableView.backgroundColor = [UIColor clearColor];
    //无色
    cell.ButtonDelegate = self;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.DayStatisticsModel = self.departmentlistArray[indexPath.row];
    //    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    [cell.detailsButton addTarget:self action:@selector(detailsButtonClick) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}
- (void)ClickDepid:(NSString *)Depid{
    self.Depid = Depid;
}
- (void)detailsButtonClick{
    MSKaoqinDayController * departVC = [[MSKaoqinDayController alloc] init];
    //    departVC.depid = model.depid;
    departVC.depid = self.Depid;
//    departVC.tagStr = @"1";
    [self.navigationController pushViewController:departVC animated:NO];
    
}
//-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//
//    MSDayStatisticsModel * model = self.departmentlistArray[indexPath.row];
//
//    MSDepartmentAttendanceController * departVC = [[MSDepartmentAttendanceController alloc] init];
//    departVC.depid = model.depid;
//    [self.navigationController pushViewController:departVC animated:NO];
//
//}

@end
